package com.atguigu.gmall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class MqConfig {
    //给RabbitTemplate配置生产者确认： 消息到达交换机的确认，消息到达队列的确认
    @Autowired
    RabbitTemplate rabbitTemplate;

    //使用jdk提供的注解：在当前类的对象实例化之后立即对rabbitTemplate进行配置
    @PostConstruct //构造器调用之后 立即调用次方法
    public void init(){
        //消息到达队列的确认
        //消息未达到队列时回调
        rabbitTemplate.setReturnCallback((Message message, int replyCode, String replyText, String exchange, String routingKey)->{
            System.out.println("消息未到达队列："+exchange+" , 路由key: "+ routingKey+
                    ", 应答码："+ replyCode+" , 原因："+ replyText+ " , 消息："+ new String(message.getBody()));
        });

        //消息到达交换机的确认
        //消息未到达交换机时回调
        rabbitTemplate.setConfirmCallback((CorrelationData correlationData, boolean ack, String cause)->{
            if(!ack){
                //ack=false消息未达到交换机
                System.out.println("消息未到达交换机, 原因："+cause);
            }
        });
    }
}
